package cn.enilu.itnews.controller;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import cn.enilu.itnews.entity.Comment;
import cn.enilu.itnews.entity.News;
import cn.enilu.itnews.entity.User;
import cn.enilu.itnews.model.CommentModel;
import cn.enilu.itnews.service.NewsService;
import org.joda.time.DateTime;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.enilu.flash.core.db.Pagination;
import cn.enilu.itnews.service.CommentService;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/comments")
public class CommentController extends BaseController {

	@Inject
	private CommentService commentService;
	@Inject
	private NewsService newsService;

	@RequestMapping(method = RequestMethod.GET)
	public String index(HttpServletRequest request, Model model) {
		Pagination<CommentModel> pagination = commentService.search(getQueryForm(request));
		model.addAttribute("comments", pagination);

		return "comments/index";
	}
	@RequestMapping(value = "/{id:^\\d+$}",method = RequestMethod.GET)
	public String list(@PathVariable("id") Long newsId,Model model){
		List<CommentModel> list = commentService.searchByNewsId(newsId);
		News news = newsService.find(newsId);
		model.addAttribute("comments",list);
		model.addAttribute("news",news);
		return "comments/list";

	}

	@RequestMapping(method = RequestMethod.POST)
	public String create(@Valid Comment comment, BindingResult result, Model model,
						 RedirectAttributes redirectAttrs) {
		User user = (User) getRequest().getSession().getAttribute("currentUser");
		if(user!=null) {
			comment.setAuthorId(user.getId());
		}
		comment.setCreateDate(DateTime.now());
		commentService.create(comment);
		return "redirect:/comments/"+comment.getNewsId();
	}



}
